<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片内容区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable v-model="pageParams.query">
            <template #append>
              <el-button :icon="Search" @click="searchUser" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <!-- 用户列表的表格 -->
      <el-table border :data="userList" stripe>
        <!-- 复选框 -->
        <el-table-column type="selection"></el-table-column>
        <!-- 索引列 -->
        <el-table-column label="编号" type="index" width="80"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <!-- admin:超级管理员，不要显示开关进行修改 -->
            <el-switch v-model="scope.row.mg_state" v-if="scope.row.id != 500" @change="changeStateHandler(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="120">
          <template #default="scope">
            <!-- 500是超级管理员，不允许修改,这里的template相当于一个包裹性质的容器，不会在dom产生额外的标签 -->
            <template v-if="scope.row.id != 500">
              <el-button size="small" type="primary" :icon="Edit" @click="showEditDialog(scope.row)"></el-button>
              <el-button size="small" type="danger" :icon="Delete" @click="removeUserById(scope.row.id)"></el-button>
              <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
                <el-button size="small" type="warning" :icon="Setting" @click="showSetRoleDialog(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:current-page="pageParams.pagenum"
        :page-sizes="pageSizes"
        v-model:page-size="pageParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>

  <!-- 添加用户的对话框, :visible.sync属性 控制窗口显示隐藏，值为addDialogVisible，默认为false -->
  <el-dialog title="添加用户" v-model="addDialogVisible" width="50%" @close="resetForm">
    <!-- 内容主体区域 -->
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="addForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <span class="dialog-footer">
      <el-button @click="resetForm">重置</el-button>
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 修改用户的对话框 -->
  <el-dialog title="修改用户" v-model="editDialogVisible" width="50%">
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
      <el-form-item label="用户名">
        <el-input v-model="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="editForm.email" prop="email"></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="editForm.mobile" prop="mobile"></el-input>
      </el-form-item>
    </el-form>
    <span class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editUser">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 分配角色对话框 -->
  <el-dialog title="分配角色" v-model="setRoleDialogVisible" width="50%">
    <el-card class="setRole">
      <el-row>
        <el-col :span="4" style="text-align: center">
          <div class="grid-content bg-purple">当前用户:</div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">{{ userInfo.username }}</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4" style="text-align: center">
          <div class="grid-content bg-purple">当前角色:</div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">{{ userInfo.role_name }}</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4" style="text-align: center">
          <div class="grid-content bg-purple">分配新角色:</div>
        </el-col>
        <el-col :span="4">
          <el-select v-model="userInfo.rid" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-col>
      </el-row>
    </el-card>
    <span class="dialog-footer">
      <el-button @click="setRoleDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { Search, Edit, Delete, Setting } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { getUserListApi, changeUserStateApi, deleteUserByIdApi, addUserApi, editUserApi, setRoleApi } from '@/api/user'
import { getRoleListApi } from '@/api/role'
import { message } from '@/utils/functions'
// 分页大小
const pageSizes = ref([3, 6, 9, 20])
// 定义分页查询参数
const pageParams = ref({
  query: '',
  pagenum: 1,
  pagesize: pageSizes.value[0]
})

// 获取用户列表数据
const userList = ref([])
const total = ref(0)
const getUserList = async () => {
  const data = await getUserListApi(pageParams.value)
  userList.value = data.users
  total.value = data.total
}

getUserList()

// 监听分页参数的变化
// 每页显示的条数发生改变时触发
const handleSizeChange = size => {
  pageParams.value.pagesize = size
  getUserList()
}
// 当前页码改变时触发
const handleCurrentChange = page => {
  pageParams.value.pagenum = page
  getUserList()
}

// 分页搜索
const searchUser = () => {
  // 重置页码
  pageParams.value.pagenum = 1
  getUserList()
}

// 修改用户状态
const changeStateHandler = async row => {
  const { id, mg_state } = row
  await changeUserStateApi(id, mg_state)
}

// 删除用户
const removeUserById = async id => {
  // 弹框询问
  const confirmResult = await ElMessageBox.confirm('您确定要删除该用户吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  // 确认删除
  if (confirmResult === 'confirm') {
    await deleteUserByIdApi(id)
    await ElMessage.success('删除成功')
    getUserList()
  }
}

// 添加用户
const addDialogVisible = ref(false)
// 添加用户的表单数据
const addForm = ref({
  username: '',
  password: '',
  email: '',
  mobile: ''
})

//定义自定义验证规则
// 验证邮箱的规则
const checkEmail = (rule, value, callback) => {
  // 验证邮箱的正则表达式
  const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

  if (regEmail.test(value)) {
    return callback()
  }
  callback(new Error('请输入合法的邮箱'))
}
// 验证手机号的规则
const checkMobile = (rule, value, callback) => {
  // 验证手机号的正则表达式
  const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
  if (regMobile.test(value)) {
    return callback()
  }

  callback(new Error('请输入合法的手机号'))
}

// 添加表单验证规则
const addFormRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      min: 1,
      max: 10,
      message: '用户名的长度在3-10个字符之间',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
    {
      min: 6,
      max: 15,
      message: '用户密码的长度在6-15个字符之间',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    {
      validator: checkEmail,
      trigger: 'blur'
    }
  ],
  mobile: [
    { required: true, message: '请输入用户手机号', trigger: 'blur' },
    { validator: checkMobile, trigger: 'blur' }
  ]
})
// 获取表单实例dom
const addFormRef = ref(null)
// 重置表单
const resetForm = () => {
  addFormRef.value.resetFields()
}
// 添加用户
const addUser = async () => {
  // 验证表单
  addFormRef.value.validate(async valid => {
    if (!valid) return
    // 验证通过
    await addUserApi(addForm.value)
    message('success', '添加用户成功')
    // 添加成功后关闭对话框
    addDialogVisible.value = false
    getUserList()
  })
}

// 修改数据
// 显示修改用户的对话框
const editDialogVisible = ref(false)
// 修改用户的表单数据
const editForm = ref({
  id: '',
  username: '',
  email: '',
  mobile: ''
})
// 校验
const editFormRules = ref({
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    {
      validator: checkEmail,
      trigger: 'blur'
    }
  ],
  mobile: [
    { required: true, message: '请输入用户手机号', trigger: 'blur' },
    { validator: checkMobile, trigger: 'blur' }
  ]
})
// 显示修改用户的对话框
const showEditDialog = row => {
  editDialogVisible.value = true
  // 直接将数据赋值给表单数据，会覆盖掉原来的数据
  // editForm.value = row
  editForm.value = { ...row }
}
// 获取表单实例dom
const editFormRef = ref(null)
// 提交修改
const editUser = async () => {
  // 验证表单
  editFormRef.value.validate(async valid => {
    if (!valid) return
    // 验证通过
    await editUserApi(editForm.value)
    message('success', '修改用户信息成功')
    // 关闭对话框
    editDialogVisible.value = false
    getUserList()
  })
}

// 分配角色
const setRoleDialogVisible = ref(false)
// 获取角色列表
const roleList = ref([])
const getRoleList = async () => {
  const data = await getRoleListApi()
  console.log(data)
  roleList.value = data
}
getRoleList()

// 角色对应的用户信息
const userInfo = ref({
  id: '',
  username: '',
  role_name: '',
  rid: ''
})

// 显示分配角色的对话框
const showSetRoleDialog = row => {
  setRoleDialogVisible.value = true
  userInfo.value.id = row.id
  userInfo.value.username = row.username
  userInfo.value.role_name = row.role_name
  userInfo.value.rid = row.role_id
}

// 修改用户的角色信息
const saveRoleInfo = async () => {
  const { id, rid } = userInfo.value
  await setRoleApi(id, rid)
  message('success', '分配角色成功')
  setRoleDialogVisible.value = false
  getUserList()
}
</script>

<style lang="scss" scoped>
.setRole {
  .el-row {
    margin-bottom: 20px;
  }
}
</style>